const express = require('express')
const app = express()
const port = 8888

// 过滤数据
const bodyparser = require('body-parser')
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({ extended: true }))

// 跨域
const cors = require('cors')
app.use(cors())

// 状态回报函数
app.use((req, res, next) => {
    // stauts状态200为成功，500为失败，默认为500
    res.ResInfo = function(err, status = 500, resdata = {}) {
        res.send({
            data: resdata,
            meta: {
                status,
                message: err instanceof Error ? err.message : err,
            }
        })
    }
    next()
})

// token的使用
const config = require('./token/config')
const expressJWT = require('express-jwt')
app.use(expressJWT({ secret: config.secretKey, algorithms: ['HS256'], }).unless({ path: /^\/api/ }))

// 挂载登录的路由
const UserRouter = require('./router/user')
app.use('/api', UserRouter)

// 挂载获取数据的路由
const MenuRouter = require('./router/menu')
app.use('/api', MenuRouter)

// 挂载获取 , 更改 ,管理员数据的路由
const ManagerRouter = require('./router/manager')
app.use('/api', ManagerRouter)


const ManagerCreateRouter = require('./router/managerCreate')
app.use('/api', ManagerCreateRouter)

const ManagerUpdateRouter = require('./router/managerUpdate')
app.use('/api', ManagerUpdateRouter)



// 数据验证包
const Joi = require('joi')

// 错误汇报机制
app.use((err, req, res, next) => {
    if (err instanceof Joi.ValidationError) return res.ResInfo(err)
    if (err.name == 'UnauthorizedError') return res.ResInfo("用户认证失败")
    next()
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))